package com.example.bilibili.utils;

import android.app.Activity;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Message;

import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.VideoView;


import com.example.bilibili.R;

import java.util.Timer;
import java.util.TimerTask;

import androidx.annotation.AttrRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

/**
 * Created by Gu on 2017/8/29.
 */

public class MediaController extends FrameLayout implements View.OnClickListener, SeekBar.OnSeekBarChangeListener, MediaPlayer.OnPreparedListener {

    private ImageView media_play;
    private ImageView media_fullscreen;
    private TextView media_total_time;
    private TextView media_current_time;
    private SeekBar media_seekBar;
    private MediaControllerListener listener;
    private VideoView videoView;
    private ProgressBar progressBar;
    private Context context;
    private boolean isHorizontal = false;
    private boolean fullscreen = false;

    private Timer timer = new Timer();
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1000:
                    if (videoView.isPlaying())
                        media_seekBar.setProgress(videoView.getCurrentPosition());
                    break;
            }
        }
    };


    public MediaController(@NonNull Context context) {
        super(context);
        loadRoot(context);
    }

    public MediaController(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        loadRoot(context);
    }

    public MediaController(@NonNull Context context, @Nullable AttributeSet attrs, @AttrRes int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        loadRoot(context);
    }


    private void loadRoot(Context context) {
        this.context = context;
        View view = LayoutInflater.from(context).inflate(R.layout.media_controller, this, true);
        initView(view);
    }

    private void initView(View view) {
        media_play = (ImageView) view.findViewById(R.id.media_play);
        media_play.setOnClickListener(this);
        media_fullscreen = (ImageView) view.findViewById(R.id.media_fullscreen);
        media_fullscreen.setOnClickListener(this);
        media_total_time = (TextView) view.findViewById(R.id.media_total_time);
        media_current_time = (TextView) view.findViewById(R.id.media_current_time);
        media_seekBar = (SeekBar) view.findViewById(R.id.media_seekbar);
        media_seekBar.setOnSeekBarChangeListener(this);
    }

    public void setMediaControllerListener(MediaControllerListener listener) {
        this.listener = listener;
    }

    public void relateVideoView(VideoView videoView) {
        this.videoView = videoView;
    }

    public void relateVvWithPb(VideoView videoView, ProgressBar progressBar) {
        this.videoView = videoView;
        this.progressBar = progressBar;
    }

    public void start(String url) {
        videoView.setVideoURI(Uri.parse(url));
        videoView.setOnPreparedListener(this);
        videoView.start();
        media_play.setImageResource(R.mipmap.media_pause);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.media_play:
                if (videoView.isPlaying()) {
                    videoView.pause();
                    media_play.setImageResource(R.mipmap.media_play);
                } else {
                    videoView.start();
                    media_play.setImageResource(R.mipmap.media_pause);
                }
                break;
            case R.id.media_fullscreen:
                setFullScreen();
                break;
        }
    }

    @Override
    public void onPrepared(MediaPlayer mp) {
        int[] time = getMinuteAndSecond(videoView.getDuration());
        media_seekBar.setMax(videoView.getDuration());
        media_total_time.setText(String.format("%02d:%02d", time[0], time[1]));
        mp.setOnVideoSizeChangedListener(new MediaPlayer.OnVideoSizeChangedListener() {
            @Override
            public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
                //获取视频资源的宽度
                int mVideoWidth = mp.getVideoWidth();
                //获取视频资源的高度
                int mVideoHeight = mp.getVideoHeight();
                isHorizontal = mVideoWidth / mVideoHeight > 0 ? true : false;
            }
        });

        mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                media_seekBar.setProgress(videoView.getDuration());
                media_play.setImageResource(R.mipmap.media_play);
            }
        });

        mp.setOnInfoListener(new MediaPlayer.OnInfoListener() {
            @Override
            public boolean onInfo(MediaPlayer mp, int what, int extra) {
                if (what == MediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START)
                    if (progressBar != null && progressBar.isShown())
                        progressBar.setVisibility(View.GONE);
                return false;
            }
        });

        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                handler.sendEmptyMessage(1000);
            }
        }, 0, 1000);

    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        int[] time = getMinuteAndSecond(progress);
        media_current_time.setText(String.format("%02d:%02d", time[0], time[1]));
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        videoView.seekTo(seekBar.getProgress());
        videoView.start();
        media_play.setImageResource(R.mipmap.media_pause);
    }

    private int[] getMinuteAndSecond(int mils) {
        mils /= 1000;
        int[] time = new int[2];
        time[0] = mils / 60;
        time[1] = mils % 60;
        return time;
    }

    private void setFullScreen() {
        if (!fullscreen) {
            boolean playing = videoView.isPlaying();
            if (isHorizontal) {
                // 设置当前activity为横屏
                ((Activity) context).setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            }
            if (!playing) {
                videoView.pause();
            }
            //设置全屏模式
            listener.isFullScreen();
            fullscreen = true;
        } else {
            boolean playing = videoView.isPlaying();
            if (isHorizontal) {
                // 设置当前activity为竖屏
                ((Activity) context).setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            }
            if (!playing) {
                videoView.pause();
            }
            listener.isLittleScreen();
            fullscreen = false;
        }
    }

}
